package com.dfdchem.imd.kaiwu.activity.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.callback.NavigationCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.dfdchem.imd.kaiwu.R;
import com.dfdchem.imd.kaiwu.application.KWApp;
import com.dfdchem.imd.kaiwu.constant.RouterPath;
import com.dfdchem.imd.kaiwu.fragment.CommonDialog;
import com.dfdchem.imd.kaiwu.fragment.FullImageDialog;
import com.dfdchem.imd.kaiwu.manager.DataManager;
import com.dfdchem.imd.kaiwu.util.Log;
import com.dfdchem.imd.kaiwu.util.StringUtil;
import com.dfdchem.imd.kaiwu.util.UrlParse;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;

import java.util.Map;


/**
 * 所有Activity的基类
 * 集成友盟统计功能的Activity，适用于页面没有复杂的逻辑，例如引导页，闪屏页
 */
public class BaseActivityUM extends AppCompatActivity {

    private static final String TAG = "BaseActivityUM";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // requestWindowFeature(Window.FEATURE_NO_TITLE);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // 禁用横屏
        ActionBar actionBar =  getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }

        ARouter.getInstance().inject(this);

        Intent intent = getIntent();
        Log.d(TAG, "intent:" + intent.toString());
        String action = intent.getAction();
        Log.d(TAG, "action:" + action);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, this.getClass().getSimpleName() + " onStart");
        PushAgent.getInstance(this).onAppStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, this.getClass().getSimpleName() + " onResume");
        MobclickAgent.onResume(this);

        // KWApp.getInstance().setCurrentActivity(this);
    }

    @Override
    protected void onPause() {
        clearReferences();

        super.onPause();
        Log.d(TAG, this.getClass().getSimpleName() + " onPause");
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        clearReferences();

        super.onDestroy();
    }

    private void clearReferences(){
        Activity currActivity = KWApp.getInstance().getCurrentActivity();
        if (this.equals(currActivity)) {
            // KWApp.getInstance().setCurrentActivity(null);
        }
    }

    /**
     * 用来处理App跳转打开和内链的问题
     * @param uri
     */
    public void handleScheme(Uri uri){
        Log.d(TAG, "scheme uri:" + uri);

        if (uri != null){
            String scheme = uri.getScheme();
            String host = uri.getHost();
            String path = uri.getPath();
            String query = uri.getQuery();

            Log.d(TAG, "scheme uri getScheme:" + uri.getScheme());
            Log.d(TAG, "scheme uri getHost:" + uri.getHost());
            Log.d(TAG, "scheme uri getPath:" + uri.getPath());
            Log.d(TAG, "scheme uri getQuery:" + uri.getQuery());

            /**
             * 1、URL格式为 arouter://kaiwu/kaiwu/news?a=b&c=d 时，打开指定的Activity
             * 2、跳转到指定的网页 格式为：arouter://kaiwu/kaiwu/webView?url=http%3a%2f%2fwww.baidu.com
             * 3、
             */
            Postcard postcard = null;
            if (!StringUtil.isEmpty(scheme)) {
                switch (scheme) {
                    case "http":
                    case "https":
                        postcard = ARouter.getInstance().build(DataManager.getInstance().isX5() ? RouterPath.WEB_VIEW_X5_ACTIVITY : RouterPath.WEB_VIEW_ACTIVITY);
                        // postcard = ARouter.getInstance().build(RouterPath.WEB_VIEW_X5_ACTIVITY);
                        postcard.withTransition(R.anim.right_push_in, R.anim.left_push_out);
                        postcard.withString("url", uri.toString());
                        postcard.navigation(BaseActivityUM.this);
                        break;

                    // case getResources().getString(R.string.app_scheme):
                    case "arouter":
                        if (!StringUtil.isEmpty(path)) {
                            if (path.startsWith("/kaiwu")) {
                                if (path.equals(RouterPath.WEB_VIEW_ACTIVITY)) {
                                    path = DataManager.getInstance().isX5() ? RouterPath.WEB_VIEW_X5_ACTIVITY : RouterPath.WEB_VIEW_ACTIVITY;
                                }

                                postcard = ARouter.getInstance().build(path);

                                postcard.withTransition(R.anim.right_push_in, R.anim.left_push_out);

                                Map<String, String> params = UrlParse.getUriParams(uri);

                                for (String key : params.keySet()) {
                                    postcard.withString(key, params.get(key));
                                    com.dfdchem.imd.kaiwu.util.Log.d(TAG, "scheme postcard.withString key:" + key + " value:" + params.get(key));
                                }
                                postcard.navigation(BaseActivityUM.this);
                            } else if (path.equals("/dialog")) {
                                Map<String, String> params = UrlParse.getUriParams(uri);
                                String dialogType = params.get("type");
                                if (!StringUtil.isEmpty(dialogType)) {
                                    int dialogTypeInt = (int) Integer.parseInt(dialogType);
                                    if (dialogTypeInt == CommonDialog.DialogStyle) {
                                        new CommonDialog(BaseActivityUM.this, params).show(getSupportFragmentManager(), "CommonDialog");
                                    } else if (dialogTypeInt == CommonDialog.DialogStyleFullText) {
                                        new CommonDialog(BaseActivityUM.this, params).show(getSupportFragmentManager(), "CommonDialog");
                                    } else if (dialogTypeInt == FullImageDialog.DialogStyle) {
                                        new FullImageDialog(BaseActivityUM.this, params).show(getSupportFragmentManager(), "FullImageDialog");
                                    }
                                } else {
                                    new CommonDialog(BaseActivityUM.this, params).show(getSupportFragmentManager(), "CommonDialog");
                                }
                            }
                        }
                        break;

                    default:

                        break;
                }
            }
        } /*else if (!StringUtil.isEmpty(url)) {
            Postcard postcard = ARouter.getInstance().build(RouterPath.WEB_VIEW_ACTIVITY)
                    .withString("url", url)
                    .withTransition(R.anim.right_push_in, R.anim.left_push_out);

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    postcard.navigation(BaseActivityUM.this);
                }
            }, 250);

        }*/
    }

    /** 通过ARoute 打开新的Activity
     * 打开新的Activity，向左滑入效果
     * @param uri
     * @date 2020年7月24日
     * @author yqq
     */
    public void toActivity(String uri) {
        ARouter.getInstance().build(uri).navigation(this, new NavigationCallback() {
            @Override
            public void onFound(Postcard postcard) {
                Log.d(TAG, "toActivity#onFound:" + postcard);
            }

            @SuppressLint("ShowToast")
            @Override
            public void onLost(Postcard postcard) {
                Log.e(TAG, "toActivity#onLost:" + postcard);
                Toast.makeText(BaseActivityUM.this, "Activity Route Not Found " + "uri:[" + uri + "]", Toast.LENGTH_LONG);
            }

            @Override
            public void onArrival(Postcard postcard) {
                Log.e(TAG, "toActivity#onArrival:" + postcard);
            }

            @Override
            public void onInterrupt(Postcard postcard) {
                Log.e(TAG, "toActivity#onInterrupt:" + postcard);
            }
        });
    }

    /** 通过ARoute 打开新的Activity
     * 打开新的Activity，向左滑入效果
     * @param uri
     * @date 2020年7月24日
     * @author yqq
     */
    public void toActivity(String uri, boolean isFinish) {
        ARouter.getInstance().build(uri).navigation(this, new NavigationCallback() {
            @Override
            public void onFound(Postcard postcard) {
            }

            @SuppressLint("ShowToast")
            @Override
            public void onLost(Postcard postcard) {
                Toast.makeText(BaseActivityUM.this, "Activity Route Not Found " + "uri:[" + uri + "]", Toast.LENGTH_LONG);
            }

            @Override
            public void onArrival(Postcard postcard) {
                if (isFinish) {
                    finish();
                }
            }

            @Override
            public void onInterrupt(Postcard postcard) {

            }
        });
    }

    /** 通过ARoute 打开新的Activity
     * 打开新的Activity，支持转场动画和关闭原activity
     * @param uri
     * @date 2020年7月24日
     * @author yqq
     */
    public void toActivity(String uri, boolean isFinish, int enterAnim, int exitAnim) {
        ARouter.getInstance()
                .build(uri)
                .withTransition(enterAnim, exitAnim)
                .navigation(this, new NavigationCallback() {
            @Override
            public void onFound(Postcard postcard) {
            }

            @SuppressLint("ShowToast")
            @Override
            public void onLost(Postcard postcard) {
                Toast.makeText(BaseActivityUM.this, "Activity Route Not Found " + "uri:[" + uri + "]", Toast.LENGTH_LONG);
            }

            @Override
            public void onArrival(Postcard postcard) {
                if (isFinish) {
                    finish();
                }
                overridePendingTransition(enterAnim, exitAnim);
            }

            @Override
            public void onInterrupt(Postcard postcard) {

            }
        });
    }
}
